package com.shanghaionstar.test;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.onstar.cn.auth.AuthTokenEntity;
import com.onstar.cn.auth.userProfile.AppVersion;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.ForgotPassWebHandler;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.Model.IUser;
import com.shanghaionstar.login.Model.UserModel;
import com.shanghaionstar.login.Model.ValidityResult;
import com.shanghaionstar.login.iview.ILoginView;
import com.shanghaionstar.login.register.JoinMeVinActivity;
import com.shanghaionstar.login.service.LoginSerice;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 6335yz on 2016/6/28.
 */
public class LoginPresenter extends BasePresenter<Class<?>> {

    private LoginSerice loginSerice;
    private ILoginView loginView;
    private Subscription subscription;
    private String tempMaskLoginName;
    private Context context;
    private IUser user;
    private boolean isJumpForgetPassword = false;
    private String name;

    protected PreferencesUtls preferences = PreferencesUtls.getInstance(OnstarApplication.getApplication());

    public LoginPresenter(IMVPScheduler mvpScheduler, Context context) {
        super(mvpScheduler);
        this.context = context;
    }

    @Override
    public void setView(IMVPView<Class<?>> view) {
        super.setView(view);
        loginView = (ILoginView) view;
        loginSerice = new LoginSerice(view.onActivity());
    }

    public void login(String userName, String password) {
        if (userName.contains("*") && tempMaskLoginName.equals(userName)) {
            userName = preferences.getString(FinalConstants.SharedPreferencesConfig.LOGIN_NAME_KEY);
        }
        user = new UserModel(userName, password);
        sendReport(FunctionNameFindId.loginregister_Login);
        ValidityResult code = user.checkUserValidity(userName, password);
        switch (code) {
            case CREDENTIAL_ALL_NULL:
                loginView.onResponseError(new OnStarException("", context.getString(R.string.name_not_null)));
                break;
            case CREDENTIAL_ONE_NULL:
                credentialBlankAlert(userName, password);
                break;
            default:
                name = userName;
                loginView.setLoading(true);
                ApplicationUtil.getInstance().setAutoLoging(true);




                subscription = loginSerice
                        .login(userName, password)
                        .flatMap(new Func1<AuthTokenEntity, Observable<Subscriber>>() {
                            @Override
                            public Observable<Subscriber> call(AuthTokenEntity authTokenEntity) {
                                return loginSerice.loadUserProfile();
                            }
                        })
                        .filter(new Func1<Subscriber, Boolean>() {
                            @Override
                            public Boolean call(Subscriber subscriber) {
                                if (!subscriber.isAppFlag()){
                                    BusinessUtil.sendReportByClickType(context, FunctionNameFindId.Login_Info3UnverifiedUserVerification.getStringValue());
                                    return true;
                                }else {
                                    return subscriber != null && !subscriber.isEmptyPhoneNo();
                                }
                            }
                        })
                        .subscribeOn(mvpScheduler.backgroundThread())
                        //失败时重复三遍

                        .observeOn(mvpScheduler.mainThread())
                        .subscribe(new Action1<Subscriber>() {
                            @Override
                            public void call(Subscriber subscriber) {
                                //获取到的Subscriber数据
                                if (!subscriber.isAppFlag()) {//是info3.0但非app或微信注册用户跳转验证页面
                                    if (loginView != null) {
                                        loginView.verifyInfo3();
                                        loginView.setLoading(false);
//                                        loginView.onFinish();
                                    }
                                } else {
                                    if (!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
                                            && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                                        /**
                                         * 访客直接成功登陆，不需要执行vehicle feature 方法
                                         */
                                    } else {
                                        /**
                                         * tdb 没有处理 UPGRADE_NEW_VERSION_OPTIONAL？
                                         */
                                        if (subscriber != null && subscriber.getApp() != null) {
                                            AppVersion app = subscriber.getApp();
                                            if (!CommonUtil.isNull(app.getVersionCode()) && CommonUtil.isInt(app.getVersionCode())) {
                                                if (Integer.parseInt(app.getVersionCode()) > new DeviceUtil(context).getAppVersionCode()) {
//                                                    resultListener.onSuccess(AuthorizeType.UPGRADE_NEW_VERSION_OPTIONAL);
                                                }
                                            }
                                        }
                                    }
//                                onSuccess();
                                    preferences.putString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME,
                                            CommonUtil.maskLoginName(name));
                                    if (!CommonUtil.isNull(name))
                                        preferences.putString(FinalConstants.SharedPreferencesConfig.LOGIN_NAME_KEY, name);
                                    if (loginView != null) {
                                        loginView.setLoading(false);
                                        loginView.onFinish();
                                    }
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                //里面抛出的Error信息
                                ApplicationUtil.getInstance().setAutoLoging(false);
                                OnStarException onStarException = (OnStarException) throwable;
                                AuthorUtil.getInstance().loginOut(context);
                                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.loginregister_Login.getStringValue(), ReportReqParam.getLoginReqParm(false,throwable.getMessage()));
                                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
                                        (context, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
                                /**
                                 * 強制升級
                                 */
                                if (!CommonUtil.isNull(onStarException.getErrorCode())
                                        && onStarException.getErrorCode().equalsIgnoreCase(ErrorEnum.E9004.getStringValue())) {
                                    if (loginView != null) {
                                        loginView.showUpgrade(onStarException);
                                    }
                                } else {
                                    if (loginView != null) {
                                        loginView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
                                    }
                                }
                            }
                        });
                break;
        }
    }

    private void credentialBlankAlert(String userName, String password) {
        if (CommonUtil.isNull(userName))
            loginView.onResponseError(new OnStarException("", context.getString(R.string.no_null_username)));
        else if (CommonUtil.isNull(password))
            loginView.onResponseError(new OnStarException("", context.getString(R.string.no_null_password)));
    }

    public void doRegister() {
        sendReport(FunctionNameFindId.loginregister_Register);
        navigateToActivity(JoinMeVinActivity.class);
    }

    public void forgetPwd() {
        isJumpForgetPassword = true;
        sendReport(FunctionNameFindId.loginregister_PasswordReset);
        navigateToForgotPass();
//        navigateToActivity(ForgotPassActivity.class);
    }

    private void navigateToForgotPass() {
        WebDataEntity entity = new WebDataEntity();
        entity.setTopTitle(context.getString(R.string.retrieve_password));
        entity.setClzName(ForgotPassWebHandler.class.getName());
        entity.setWhat(IWebType.TYPE_FORGOT_PASS);
        CommonWebViewActivity.launchCommonWeb((Activity) context,entity);
    }

    public void unRegisterSubscriber() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }

    /**
     * tbd 处理report逻辑
     *
     * @param functionNameFindId
     */
    public void sendReport(FunctionNameFindId functionNameFindId) {
        //处理调用report逻辑
        BusinessUtil.sendReportByClickType(OnstarApplication.getApplication(), functionNameFindId.getStringValue());
    }

    public void navigateToActivity(Class clazz) {
        navigateToActivity(clazz, null, null);
    }

    public void navigateToActivity(Class clazz, Bundle bundle, Intent intent) {
        if (intent == null) {
            Intent newIntent = new Intent(context, clazz);
            if (bundle != null) {
                newIntent.putExtras(bundle);
            }
            context.startActivity(newIntent);
        } else {
            context.startActivity(intent);
        }
    }


    public void onResume() {
        tempMaskLoginName = preferences.getString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME);
        String displayLoginName;
        if (!isJumpForgetPassword) {
            displayLoginName = preferences.getString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME);
        } else {
            isJumpForgetPassword = false;
            displayLoginName = "";
        }
        loginView.setEditNameValue(displayLoginName);
        loginView.setEditPwdValue("");
    }

}
